package com.syn.synold4s.activity;

import static com.gaoyi.basemodule.baseUtil.PermissionUtils.checkLocationPermission;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
import static com.syn.synold4s.constants.ResultCode.RESULT_MAP;
import static com.syn.synold4s.constants.TagCode.API_KEY;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gaoyi.basemodule.baseAdapter.BaseAdapter;
import com.gaoyi.basemodule.baseCallback.IView;
import com.gaoyi.basemodule.baseUtil.AppUtil;
import com.gaoyi.basemodule.baseUtil.DensityUtil;
import com.gaoyi.basemodule.baseUtil.GsonUtil;
import com.gaoyi.basemodule.baseUtil.LanguageUtils;
import com.gaoyi.basemodule.baseUtil.OKHttpUtil;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.SmartRefreshUtil;
import com.gaoyi.basemodule.baseUtil.ThreadManager;
import com.gaoyi.basemodule.baseUtil.ToastUtil;
import com.gaoyi.basemodule.baseUtil.WindowUtil;
import com.gaoyi.basemodule.basebean.LoginDto;
import com.gaoyi.basemodule.basebean.ProjectDto;
import com.gaoyi.basemodule.basebean.UserTagDto;
import com.gaoyi.basemodule.baseconstant.ApiStatus;
import com.gaoyi.basemodule.baseconstant.Constants;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.gaoyi.basemodule.basedialog.LoadingDialogUtils;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.gson.reflect.TypeToken;
import com.syn.synold4s.R;
import com.syn.synold4s.activity.base.BaseAlertActivity;
import com.syn.synold4s.activity.google_map.GoogleMapActivity;
import com.syn.synold4s.activity.instant_analysis.DriverStatusMonitoringActivity;
import com.syn.synold4s.activity.instant_analysis.HazardousGasMonitoringActivity;
import com.syn.synold4s.activity.instant_analysis.MonitoringPlantActivity;
import com.syn.synold4s.activity.instant_analysis.PermitToWorkActivity;
import com.syn.synold4s.activity.instant_analysis.SafetyTrainingActivity;
import com.syn.synold4s.activity.instant_analysis.SmartLockActivity;
import com.syn.synold4s.activity.instant_analysis.SmartWatchActivity;
import com.syn.synold4s.activity.instant_analysis.TowerCraneActivity;
import com.syn.synold4s.activity.instant_analysis.TrackingSystemActivity;
import com.syn.synold4s.activity.instant_analysis.UnsafeActActivity;
import com.syn.synold4s.activity.setting.SettingActivity;
import com.syn.synold4s.activity.surveillance.SurveillanceActivity;
import com.syn.synold4s.adapter.AlertAdapter;
import com.syn.synold4s.adapter.DrawerAdapter;
import com.syn.synold4s.adapter.MainLockAdapter;
import com.syn.synold4s.adapter.MainPlant360Adapter;
import com.syn.synold4s.adapter.PermitToWorkAdapter;
import com.syn.synold4s.adapter.SafetyTrainingAdapter;
import com.syn.synold4s.adapter.TableViewAdapter;
import com.syn.synold4s.adapter.UnsafeActAdapter;
import com.syn.synold4s.adapter.WatchAdapter;
import com.syn.synold4s.adapter.WeatherAdapter;
import com.syn.synold4s.bean.dto.AiDto;
import com.syn.synold4s.bean.dto.AssetDto;
import com.syn.synold4s.bean.dto.GasMonitoringDto;
import com.syn.synold4s.bean.dto.GassDto;
import com.syn.synold4s.bean.dto.LockDto;
import com.syn.synold4s.bean.dto.PermitToWorkDto;
import com.syn.synold4s.bean.dto.ShortDto;
import com.syn.synold4s.bean.dto.WatchListDto;
import com.syn.synold4s.constants.TagCode;
import com.syn.synold4s.control.ProjectPopupWindow;
import com.syn.synold4s.control.ShortPopupWindow;
import com.syn.synold4s.control.dialog.GoogleMapLockDialog;
import com.syn.synold4s.control.dialog.LockDialog;
import com.syn.synold4s.control.dialog.WatchDialog;
import com.syn.synold4s.databinding.ActivityMainBinding;
import com.syn.synold4s.databinding.Main360Binding;
import com.syn.synold4s.databinding.MainAiBinding;
import com.syn.synold4s.databinding.MainAlertBinding;
import com.syn.synold4s.databinding.MainGasBinding;
import com.syn.synold4s.databinding.MainLockBinding;
import com.syn.synold4s.databinding.MainPermitToWorkBinding;
import com.syn.synold4s.databinding.MainSafetyTrainingBinding;
import com.syn.synold4s.databinding.MainTrackingSystemBinding;
import com.syn.synold4s.databinding.MainUnsafeActBinding;
import com.syn.synold4s.databinding.MainWatchBinding;
import com.syn.synold4s.receiver.MqttNotifyReceiver;
import com.syn.synold4s.service.CloseService;
import com.syn.synold4s.util.GoogleMapUtils;
import com.syn.synold4s.util.MyAnimUtil;
import com.syn.synold4s.vm.MainViewModel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseAlertActivity<ActivityMainBinding, MainViewModel> implements OnMapReadyCallback, IView {

    private ActivityResultLauncher<Intent> mResultMap;
    private String mProjId;
    private MainPermitToWorkBinding mPermitToWork;
    private PermitToWorkAdapter mPTWAdapter;
    private MainSafetyTrainingBinding mSafetyTraining;
    private SafetyTrainingAdapter mSafetyAdapter;
    private MainGasBinding mGas;
    private TableViewAdapter mGasAdapter;
    private MainWatchBinding mWatch;
    private WatchAdapter mWatchAdapter;
    private MainLockBinding mLock;
    private MainLockAdapter mLockAdapter;
    private MainTrackingSystemBinding mTracking;
    private Main360Binding m360;
    private MainPlant360Adapter mPlant360Adapter;
    private MainAlertBinding mAlert;
    private AlertAdapter mAlertAdapter;
    private MainUnsafeActBinding mUnsafeAct;
    private UnsafeActAdapter mUnsafeActAdapter;
    private MainAiBinding mAi;
    private WeatherAdapter mWeatherAdapter;
    private DrawerAdapter mDrawerAdapter;
    private ProjectPopupWindow mProjectPopupWindow;
    private ShortPopupWindow mAlertPopupWindow;
    private String TAG = "TAG";
    private Timer mTimer;
    private boolean mIsShow = true;
    private GoogleMap map;
    private LatLng defaultLocation;
    private float DEFAULT_ZOOM = 18;
    private String tagCode;
    private String mAlertName = "";
    private String mAlertCode = "";
    private boolean watchIsShow = true;
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private String queryInfoTagCode = "";
    private WatchListDto watchOldData;
    private LockDto lockOldData;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        WindowUtil.setWindowDecorView(this);
        defaultLocation = new LatLng(Double.parseDouble(SPUtil.getInstance().getString(SPName.PROJ_LAT, "22.347288")),
                Double.parseDouble(SPUtil.getInstance().getString(SPName.PROJ_LNG, "114.130737")));
        startCloseService(SPUtil.getInstance().getString(SPName.PROJ_CODE));
        mResultMap = registerForActivityResult(RESULT_MAP);
        mPermissionsResult = registerForPermissionsResult();
        // 天气列表
        mWeatherAdapter = new WeatherAdapter(this);
        mBinding.mainInfo.rvWeather.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        mBinding.mainInfo.rvWeather.setAdapter(mWeatherAdapter);
        mBinding.mainInfo.tvInfoLocation.setText(SPUtil.getInstance().getString(SPName.PROJ_ADDRESS));
        initSmartRefreshLayout();
        initListener();
        initMap();
        initDrawer();
        registerNotifyReceiver();
    }

    /**
     * 监听mqtt报警广播
     */
    private void registerNotifyReceiver() {
        MqttNotifyReceiver mReceiver = new MqttNotifyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MqttNotifyReceiver.MY_ACTION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(mReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(mReceiver, filter);
        }
    }

    private void initDrawer() {
        mBinding.tvVersion.setText("V" + AppUtil.getVersion());
        mBinding.tvSetting.setOnClickListener(view -> {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(this, SettingActivity.class));
        });
        mBinding.mainToolbar.setOnBackListener(() -> mBinding.drawerLayout.openDrawer(GravityCompat.START));
        mBinding.tvDeviceStatus.setSelected(true);
        mBinding.tvDeviceStatus.setOnClickListener(view -> {
            boolean status = !mBinding.tvDeviceStatus.isSelected();
            mBinding.tvDeviceStatus.setSelected(status);
            MyAnimUtil.startAnim(mBinding.rvDeviceStatus, !status);
        });
        mBinding.tvLocation.setOnClickListener(view -> {
            startMapAct();
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        });
        mBinding.tvSurveillance.setOnClickListener(view -> {
            startActivity(new Intent(this, SurveillanceActivity.class));
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        });
        mDrawerAdapter = new DrawerAdapter(this);
        mDrawerAdapter.setOnItemClickListener((v, position) -> {
            String code = mDrawerAdapter.getCurrentList().get(position).getCode();
            if (code == null) {
                mBinding.nestedScrollView.scrollTo(0, 0);
            } else {
                switch (code) {
                    case TagCode.codePermitToWork:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mPermitToWork.titlePermitToWork));
                        startActivity(new Intent(mContext, PermitToWorkActivity.class));
                        break;
                    case TagCode.codeSafetyTraining:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mSafetyTraining.titlePermitToWork));
                        startActivity(new Intent(mContext, SafetyTrainingActivity.class));
                        break;
                    case TagCode.codeGas:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mGas.titlePermitToWork));
                        startActivity(new Intent(mContext, HazardousGasMonitoringActivity.class));
                        break;
                    case TagCode.codeWatch:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mWatch.titlePermitToWork));
                        startActivity(new Intent(mContext, SmartWatchActivity.class));
                        break;
                    case TagCode.codeLock:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mLock.titlePermitToWork));
                        startActivity(new Intent(mContext, SmartLockActivity.class));
                        break;
                    case TagCode.codeTowerCrane:
                        startActivity(new Intent(mContext, TowerCraneActivity.class));
                        break;
                    case TagCode.codeTracking:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mTracking.titlePermitToWork));
                        startActivity(new Intent(mContext, TrackingSystemActivity.class));
                        break;
                    case TagCode.code360:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(m360.titlePermitToWork));
                        startActivity(new Intent(mContext, MonitoringPlantActivity.class));
                        break;
                    case TagCode.codeAlert:
                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mAlert.titlePermitToWork));
                        break;
                    case TagCode.codeUnSafeAct:
//                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mUnsafeAct.titleUnsafeAct));
                        startActivity(new Intent(mContext, UnsafeActActivity.class));
                        break;
                    case TagCode.codeAi:
                        mBinding.nestedScrollView.smoothScrollTo(0, MyAnimUtil.getTargetY(mAi.titlePermitToWork));
                        break;
                    case TagCode.codeDriver:
                        startActivity(new Intent(mContext, DriverStatusMonitoringActivity.class));
                        break;
                }
            }
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        });
        mBinding.rvDeviceStatus.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvDeviceStatus.setAdapter(mDrawerAdapter);
    }

    private void startMapAct() {
        mResultMap.launch(new Intent(this, GoogleMapActivity.class));
    }

    private void closePopupWindow() {
        if (mAlertPopupWindow != null && mAlertPopupWindow.isShowing()) {
            mAlertPopupWindow.dismiss();
        }
        if (mProjectPopupWindow != null && mProjectPopupWindow.isShowing()) {
            mProjectPopupWindow.dismiss();
        }
    }

    private void initSmartRefreshLayout() {
        mBinding.smartRefreshLayout.setTag(Constants.REFRESH);
        //刷新
        mBinding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            mBinding.smartRefreshLayout.setTag(Constants.REFRESH);
            mViewModel.getData();
        });
    }

    /**
     * 项目列表下拉框
     */
    private void showProjectPopup() {
        if (mProjectPopupWindow == null) {
            mProjectPopupWindow = new ProjectPopupWindow(mContext);
            mProjectPopupWindow.setHeight(DensityUtil.dp2px(300));
            mProjectPopupWindow.setDropDownGravity(Gravity.END);
            mProjectPopupWindow.setAnchorView(mBinding.mainInfo.tvProjectName);
            mProjectPopupWindow.setWidth(DensityUtil.dp2px(200));
            mProjectPopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
                mProjectPopupWindow.dismiss();
                if (mProjId.equals(mViewModel.getProject().getValue().get(i).getId())) {
                    return;
                }
                ProjectDto shortDto = mViewModel.getProject().getValue().get(i);
                mProjId = shortDto.getId();
                handleProjectTag(shortDto);
                SPUtil.getInstance().putString(SPName.PROJ_ID, shortDto.getId());
                SPUtil.getInstance().putString(SPName.PROJ_CODE, shortDto.getCode());
                stopService(new Intent(this, CloseService.class));
                startCloseService(shortDto.getCode());
            });
            mProjectPopupWindow.setOnDismissListener(() -> mBinding.mainInfo.tvProjectName.setSelected(false));
        }
        mProjectPopupWindow.setData(mViewModel.getProject().getValue(), mProjId);
        mBinding.mainInfo.tvProjectName.setSelected(true);
        mProjectPopupWindow.show();
    }

    /**
     * 开启前台服务
     */
    private void startCloseService(String code) {
        Intent intent = new Intent(this, CloseService.class);
        intent.putExtra(SPName.PROJ_CODE, code);
        intent.putExtra(SPName.MAP_TYPE, LanguageUtils.getInstance().getMapLanguage());
        startService(intent);
    }

    private void initListener() {
        mBinding.mainMap.ivZoom.setOnClickListener(view -> startMapAct());
        mBinding.mainInfo.tvProjectName.setOnClickListener(view -> {
            // 没有项目列表，重新请求获取
            if (mViewModel.getProject().getValue().isEmpty()) {
                mViewModel.getProjectList();
                return;
            }
            showProjectPopup();
        });
    }

    private void initMap() {
        // 构造 PlacesClient
        Places.initialize(getApplicationContext(), API_KEY);
        Places.createClient(this);

        // 构造 FusedLocationProviderClient
        // 融合位置信息提供程序的入口点
        FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        //初始化视图
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        this.map = googleMap;
        if (checkLocationPermission(mContext, mPermissionsResult)) {
            configMap();
        }
    }

    /**
     * 地图配置
     */
    private void configMap() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        map.setMyLocationEnabled(true);
        map.setMapType(MAP_TYPE_SATELLITE);
        // 地图UI设置
        GoogleMapUtils.uiSettings(map, false);
        //
        map.setOnMarkerClickListener(marker -> {
            String[] str = (String[]) marker.getTag();
            tagCode = str[0];
            return false;
        });
        //设置默认位置
        changeMapCenter(defaultLocation);
    }

    private String splitAddress(String address) {
        String[] split = address.split("省|市");
        return split[split.length - 1].replace(",", "");
    }

    /**
     * 改变地图中心
     */
    private void changeMapCenter(LatLng latLng) {
        // 地图中移动到经纬度处
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
    }

    @Override
    protected int initVariable() {
        return 0;
    }

    @Override
    protected void initLiveData() {
        // 获取项目列表
        mViewModel.getProject().observe(this, this::handleProjects);
        mViewModel.getResultCode().observe(this, data -> {
            if (data == ApiStatus.SUCCESS) {
                showProjectPopup();
            } else {
                ToastUtil.showToast(R.string.network_error);
            }
        });
        // 獲取項目對應的子模塊
        mViewModel.getTagByProj().observe(this, this::handleTag);
        // 获取报警类型列表
        mViewModel.getAlertTypes().observe(this, this::handleAlertType);
        mViewModel.getAlertResultCode().observe(this, data -> {
            if (data == ApiStatus.SUCCESS) {
                showAlertTypePopup();
            } else {
                ToastUtil.showToast(R.string.network_error);
            }
        });
        // 天气列表
        mViewModel.getWeather().observe(this, data -> mWeatherAdapter.submitList(data));
        // PermitToWork
        mViewModel.getPermitToWork().observe(this, data -> {
            if (mPermitToWork == null) {
                return;
            }
            initPermitToWork(data);
            mPTWAdapter.submitList(data);
        });
        mViewModel.getStatusPTW().observe(this, data -> {
            if (data != null) {
                mPermitToWork.titlePermitToWork.setStatus(data);
            }
        });
        // GasMonitoring
        mViewModel.getGasMonitoring().observe(this, data -> {
            if (mGas == null) {
                return;
            }
            initGas();
            initGasData(data);
        });
        mViewModel.getStatusGas().observe(this, data -> {
            if (data != null) {
                mGas.titlePermitToWork.setStatus(data);
            }
        });
        // Vr
        mViewModel.getVrs().observe(this, data -> {
            if (mSafetyTraining == null) {
                return;
            }
            initSafetyTraining();
            mSafetyAdapter.submitList(data);
        });
        mViewModel.getStatusVrs().observe(this, data -> {
            if (data != null) {
                mSafetyTraining.titlePermitToWork.setStatus(data);
            }
        });
        // Watch
        mViewModel.getWatch().observe(this, data -> {
            if (mWatch == null) {
                return;
            }
            if (null != data && data.size() > 0) {
                for (WatchListDto dto : data) {
                    dto.setShow(watchIsShow);
                }
            }
            initWatch();
            mWatchAdapter.submitList(data);
        });
        mViewModel.getStatusWatch().observe(this, data -> {
            if (data != null) {
                mWatch.titlePermitToWork.setStatus(data);
            }
        });
        // Lock
        mViewModel.getLock().observe(this, data -> {
            if (mLock == null) {
                return;
            }
            initLock();
            mLockAdapter.submitList(data);
        });
        mViewModel.getStatusLock().observe(this, data -> {
            if (data != null) {
                mLock.titlePermitToWork.setStatus(data);
            }
        });
        // Tracking System
        mViewModel.getAsset().observe(this, this::initTrackingData);
        mViewModel.getStatusAsset().observe(this, data -> {
            if (data != null) {
                mTracking.titlePermitToWork.setStatus(data);
            }
        });
        // 360 MONITORING PLANT
        mViewModel.getHelmet().observe(this, data -> {
            if (m360 == null || data.getList() == null) {
                return;
            }
            init360();
            mPlant360Adapter.submitList(data.getList());
            m360.tvAntiCollision.setText(data.getAntiCollTotal()+"");
        });
        mViewModel.getStatusHelmet().observe(this, data -> {
            if (data != null) {
                m360.titlePermitToWork.setStatus(data);
            }
        });
        // Alert
        mViewModel.getAlert().observe(this, data -> {
            if (mAlert == null) {
                return;
            }
            initAlert();
            mAlertAdapter.submitList(data);
        });
        mViewModel.getStatusAlert().observe(this, data -> {
            if (data != null) {
                mAlert.titlePermitToWork.setStatus(data);
            }
        });
        // Unsafe Act
        mViewModel.getUnSafeAct().observe(this, data -> {
            if (mUnsafeAct == null) {
                return;
            }
            initUnsafeAct();
            mUnsafeActAdapter.submitList(data);
        });
        mViewModel.getStatusUnSafeAct().observe(this, data -> {
            if (data != null) {
                mUnsafeAct.titleUnsafeAct.setStatus(data);
            }
        });
        // Ai
        mViewModel.getAi().observe(this, this::initAiData);
        mViewModel.getStatusAi().observe(this, data -> {
            if (data != null) {
                mAi.titlePermitToWork.setStatus(data);
            }
        });
        mViewModel.getMapAllDevice().observe(mContext, mapDevice -> {
            if (mapDevice != null && map != null) {
                map.clear();
                mapDevice.forEach(device -> GoogleMapUtils.createMarkers(map, mContext, device));
            }
        });
        //地址转换
        mViewModel.getAddress().observe(this, addressDto -> {
            if (addressDto.getPlus_code() != null) {
                if (!TextUtils.isEmpty(addressDto.getPlus_code().getCompound_code())) {
                    String addressInfo = addressDto.getPlus_code().getCompound_code();
                    String address = splitAddress(addressInfo);
                    mBinding.mainInfo.tvInfoLocation.setText(address);
                }
            }
        });
        mViewModel.getMapDeviceDetails().observe(mContext, deviceDetails -> GoogleMapUtils.showDialog(mContext, deviceDetails, tagCode));
        mViewModel.getRefreshResultCode().observe(mContext, resultCode -> SmartRefreshUtil.refreshSmartRefreshLayout(mBinding.smartRefreshLayout));

        //设备总数 All device
        mViewModel.getAllMainDto().observe(this, mainDto -> {
            if (null != mainDto.getWatch()) {//手表
                mWatch.titlePermitToWork.setAllDevice(null == mainDto.getWatch().getDeviceOnlineTotal() ? 0 : mainDto.getWatch().getDeviceOnlineTotal()
                        , null == mainDto.getWatch().getDeviceTotal() ? 0 : mainDto.getWatch().getDeviceTotal());
                mWatch.tvSos.setText(mainDto.getWatch().getSos() + "");
            } else if (null != mainDto.getEleclock()) {//电子锁
                mLock.titlePermitToWork.setAllDevice(null == mainDto.getDeviceOnlineTotal() ? 0 : mainDto.getDeviceOnlineTotal()
                        , null == mainDto.getDeviceTotal() ? 0 : mainDto.getDeviceTotal());
            } else if (null != mainDto.getHelmet()){//360
                m360.titlePermitToWork.setAllDevice(null == mainDto.getDeviceOnlineTotal() ? 0 : mainDto.getDeviceOnlineTotal()
                        , null == mainDto.getDeviceTotal() ? 0 : mainDto.getDeviceTotal());
            }
        });

        //
        mViewModel.getDeviceInfoResult().observe(this, data->{
            if (TagCode.codeWatch.equals(queryInfoTagCode)){
                new WatchDialog(mContext, watchOldData, data).show(getSupportFragmentManager());
            } else if (TagCode.codeLock.equals(queryInfoTagCode)){
                new LockDialog(mContext, lockOldData, data).show(getSupportFragmentManager());
            }
        });
    }

    /**
     * 处理返回的报警类型列表，显示选择的报警类型在报警模块的选择框内
     */
    private void handleAlertType(List<ShortDto> data) {
        boolean isAll = true;
        StringBuilder names = new StringBuilder();
        if (TextUtils.isEmpty(mAlertCode)) {
            mAlertName = getString(R.string.all);
        } else {
            for (ShortDto dto : data) {
                if (mAlertCode.contains(dto.getCode())) {
                    names.append(",").append(dto.getName());
                } else {
                    isAll = false;
                }
            }
            if (isAll) {
                mAlertName = getString(R.string.all);
            } else {
                if (names.toString().isEmpty()) {
                    mAlertName = "";
                } else {
                    mAlertName = names.substring(1);
                }
            }
        }
        if (mAlert != null) {
            mAlert.tvAlertType.setText(getString(R.string.alert_view, mAlertName));
        }
    }

    private void initTrackingData(AssetDto data) {
        if (mTracking == null) {
            return;
        }
        Date date = new Date();
        mTracking.viewTrackingToday.setNumAndTime(data.getExpedTotal(), date);
        mTracking.viewTracking7.setNumAndTime(data.getExpedTotal7(), date);
        mTracking.viewTracking30.setNumAndTime(data.getExpedTotal30(), date);
    }

    private void initAiData(AiDto data) {
        if (data == null) {
            mAi.viewAiIn.setNum(0);
            mAi.viewAiOut.setNum(0);
            mAi.viewAiAlert.setNum(0);
            return;
        }
        if (mAi == null) {
            return;
        }
        mAi.viewAiIn.setNum(data.getInTotal());
        mAi.viewAiOut.setNum(data.getOutTotal());
        mAi.viewAiAlert.setNum(data.getAlertTotal());
    }

    private void initGasData(List<GasMonitoringDto> data) {
        if (data.isEmpty()) {
            return;
        }
        List<GassDto> gass = data.get(0).getGass();
        if (gass == null) {
            return;
        }
        List<String> columnTitle = new ArrayList<>();
        List<String> rowTitle = new ArrayList<>();
        List<List<GassDto>> cellContent = new ArrayList<>();
        int size = gass.size();
        for (int i = 0; i < size; i++) {
            columnTitle.add(gass.get(i).getCode());
        }
        size = data.size();
        for (int i = 0; i < size; i++) {
            rowTitle.add(data.get(i).getDeviceName());
            cellContent.add(data.get(i).getGass());
        }
        mGasAdapter.setAllItems(columnTitle, rowTitle, cellContent);
    }

    /**
     * 处理主页显示的版块
     */
    private void handleUserTag(List<UserTagDto> data) {
        int childCount = mBinding.llMainContent.getChildCount();
        mBinding.llMainContent.removeViews(2, childCount - 2);
        boolean isHaveCCTV = false;
        List<UserTagDto> drawerList = new ArrayList<>();
        drawerList.add(new UserTagDto("all", getString(R.string.all_big)));
        for (UserTagDto userTagDto : data) {
            if (userTagDto.getCode().equals(TagCode.codeSurveillance)) {
                isHaveCCTV = true;
                mBinding.tvSurveillance.setText(userTagDto.getName());
            } else {
                if (Objects.equals(userTagDto.getCode(), "SynAlert") || (Objects.equals(userTagDto.getOwPage(), "All"))) {
//                && !Objects.equals(userTagDto.getCode(), "SynDSM")
//                    && !Objects.equals(userTagDto.getCode(), "SynTowerCrane")
                    drawerList.add(userTagDto);
                }
                switch (userTagDto.getCode()) {
                    case TagCode.codePermitToWork:
                        if (mPermitToWork == null) {
                            mPermitToWork = MainPermitToWorkBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                        }
                        mBinding.llMainContent.addView(mPermitToWork.getRoot());
                        initPermitToWork(null);
                        mPermitToWork.titlePermitToWork.setTitle(userTagDto.getName());
                        mPermitToWork.titlePermitToWork.setAnimView(mPermitToWork.rvPermitToWork);
                        break;
                    case TagCode.codeSafetyTraining:
                        if (mSafetyTraining == null) {
                            mSafetyTraining = MainSafetyTrainingBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                        }
                        mBinding.llMainContent.addView(mSafetyTraining.getRoot());
                        initSafetyTraining();
                        mSafetyTraining.titlePermitToWork.setTitle(userTagDto.getName());
                        mSafetyTraining.titlePermitToWork.setAnimView(mSafetyTraining.llTraining);
                        break;
                    case TagCode.codeGas:
                        initGas();
                        mBinding.llMainContent.addView(mGas.getRoot());
                        mGas.titlePermitToWork.setTitle(userTagDto.getName());
                        mGas.titlePermitToWork.setAnimView(mGas.llGas);
                        break;
                    case TagCode.codeWatch:
                        initWatchView();
                        mBinding.llMainContent.addView(mWatch.getRoot());
                        mWatch.titlePermitToWork.setTitle(userTagDto.getName());
                        mWatch.titlePermitToWork.setAnimView(mWatch.llWatch);
                        break;
                    case TagCode.codeLock:
                        initLockView();
                        mBinding.llMainContent.addView(mLock.getRoot());
                        mLock.titlePermitToWork.setTitle(userTagDto.getName());
                        mLock.titlePermitToWork.setAnimView(mLock.llLock);
                        break;
                    case TagCode.codeTracking:
                        if (mTracking == null) {
                            mTracking = MainTrackingSystemBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                        }
                        mBinding.llMainContent.addView(mTracking.getRoot());
                        mTracking.titlePermitToWork.setTitle(userTagDto.getName());
                        mTracking.titlePermitToWork.setAnimView(mTracking.llTracking);
                        break;
                    case TagCode.code360:
                        init360View();
                        mBinding.llMainContent.addView(m360.getRoot());
                        m360.titlePermitToWork.setTitle(userTagDto.getName());
                        m360.titlePermitToWork.setAnimView(m360.ll360);
                        break;
                    case TagCode.codeAlert:
                        if (mAlert == null) {
                            mAlert = MainAlertBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                            mAlert.tvAlertType.setText(getString(R.string.alert_view, mAlertName));
                            mAlert.tvAlertType.setOnClickListener(view -> {
                                // 没有报警列表，重新请求获取
                                if (mViewModel.getAlertTypes().getValue().isEmpty()) {
                                    mViewModel.getAlertList();
                                    return;
                                }
                                showAlertTypePopup();
                            });
                        }
                        mBinding.llMainContent.addView(mAlert.getRoot());
                        initAlert();
                        mAlert.titlePermitToWork.setTitle(userTagDto.getName());
                        mAlert.titlePermitToWork.setAnimView(mAlert.llAlert);
                        break;
                    case TagCode.codeUnSafeAct:
                        if (mUnsafeAct == null) {
                            mUnsafeAct = MainUnsafeActBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                        }
                        mBinding.llMainContent.addView(mUnsafeAct.getRoot());
                        initUnsafeAct();
                        mUnsafeAct.titleUnsafeAct.setTitle(userTagDto.getName());
                        mUnsafeAct.titleUnsafeAct.setAnimView(mUnsafeAct.rvUnsafeAct);
                        break;
                    case TagCode.codeAi:
                        if (mAi == null) {
                            mAi = MainAiBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
                        }
                        mBinding.llMainContent.addView(mAi.getRoot());
                        mAi.titlePermitToWork.setTitle(userTagDto.getName());
                        mAi.titlePermitToWork.setAnimView(mAi.llAi);
                        break;
//                    case TagCode.codeDriver:
//                        break;
                }
            }

        }
        mBinding.tvSurveillance.setVisibility(isHaveCCTV ? View.VISIBLE : View.GONE);
        mDrawerAdapter.submitList(drawerList);
    }

    private void showAlertTypePopup() {
        if (mAlertPopupWindow == null) {
            mAlertPopupWindow = new ShortPopupWindow(mContext);
            mAlertPopupWindow.setHeight(DensityUtil.dp2px(200));
            mAlertPopupWindow.setAnchorView(mAlert.tvAlertType);
            mAlertPopupWindow.setOnItemClickListener((adapterView, view, i, l) -> {
                mAlertPopupWindow.changeState(i);
                String[] idsAndNames = mAlertPopupWindow.getSelectIdsAndNames();
                mAlertName = idsAndNames[0];
                mAlertCode = idsAndNames[1];
                SPUtil.getInstance().putString(SPName.ALERT_CODE, mAlertCode);
                mAlert.tvAlertType.setText(getString(R.string.alert_view, mAlertName));
                mViewModel.setAlertKeyWord(mAlertCode);
                ThreadManager.getInstance().execute(() -> mViewModel.getAlert(SPUtil.getInstance().getString(SPName.PROJ_CODE)));

            });
            mAlertPopupWindow.setOnDismissListener(() -> mAlert.tvAlertType.setSelected(false));
        }
        mAlertPopupWindow.setData(mViewModel.getAlertTypes().getValue(), mAlertCode);
        mAlert.tvAlertType.setSelected(true);
        mAlertPopupWindow.show();
    }

    /**
     * 处理對應的子模塊
     */
    private void handleTag(LoginDto data) {
        List<UserTagDto> synProjs = data.getTags();
        if (synProjs != null) {
            // 主页请求的code
            List<String> codes = new ArrayList<>();
            // 需要显示的版块
            List<UserTagDto> tags = new ArrayList<>();
            StringBuilder codesStr = new StringBuilder();
            for (UserTagDto userTag : synProjs) {
                if (TextUtils.isEmpty(userTag.getCode())) {
                    continue;
                }
                if (userTag.getCode().equals(TagCode.codeSurveillance)) {
                    tags.add(userTag);
                } else {
                    if (Objects.equals(userTag.getOwPage(), "All")
                            || Objects.equals(userTag.getOwPage(), "Dashboard")
                            || !Objects.equals(userTag.getOwPage(), TagCode.codeDriver)) {
                        codes.add(userTag.getCode());
                        codesStr.append(",").append(userTag.getCode());
                        tags.add(userTag);
                    }
                }
            }
            mViewModel.setTagCodes(codes);
            handleUserTag(tags);
            SPUtil.getInstance().putString(SPName.TAG_CODE, codesStr.length() > 0 ? codesStr.substring(1) : "");
            SPUtil.getInstance().putString(SPName.TAG, GsonUtil.getInstance().toJson(tags));
        }
    }

    /**
     * 处理返回的项目列表
     * 根据ProjId获取对应的tag列表
     */
    private void handleProjects(List<ProjectDto> data) {
        for (ProjectDto project : data) {
            if (mProjId.equals(project.getId())) {
                handleProjectTag(project);
            }
        }
    }

    private void handleProjectTag(ProjectDto project) {
        mBinding.mainInfo.tvProjectName.setText(project.getName());
        mBinding.mainInfo.tvInfoLocation.setText(project.getAddress());
        SPUtil.getInstance().putString(SPName.PROJ_ADDRESS, project.getAddress());
        SPUtil.getInstance().putString(SPName.PROJ_NAME, project.getName());
    }

    private void initPermitToWork(List<PermitToWorkDto> data) {
        if (mPTWAdapter == null) {
            mPTWAdapter = new PermitToWorkAdapter(this);
            if (data != null && !data.isEmpty()) {
                int size = data.size();
                if (size == 1) {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
                } else if (size == 2) {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new GridLayoutManager(mContext, 2));
                } else {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
                }
            } else {
                mPermitToWork.rvPermitToWork.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
            }
            mPermitToWork.rvPermitToWork.setAdapter(mPTWAdapter);
            mPermitToWork.rvPermitToWork.setItemAnimator(null);
        } else {
            if (data != null && mPTWAdapter.getItemCount() != data.size()) {
                int size = data.size();
                if (size == 1) {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
                } else if (size == 2) {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new GridLayoutManager(mContext, 2));
                } else {
                    mPermitToWork.rvPermitToWork.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
                }
            }
        }
    }

    private void initSafetyTraining() {
        if (mSafetyAdapter == null) {
            mSafetyAdapter = new SafetyTrainingAdapter(this);
            mSafetyTraining.rvSafetyTraining.setLayoutManager(new LinearLayoutManager(mContext));
            mSafetyTraining.rvSafetyTraining.setAdapter(mSafetyAdapter);
            mSafetyTraining.rvSafetyTraining.setItemAnimator(null);
        }
    }

    private void initGas() {
        if (mGas == null) {
            mGas = MainGasBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
            mGas.etGas.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    // 避免错乱
                    mHandler.removeCallbacksAndMessages(null);

                    mHandler.postDelayed(() -> {
                        String search = editable.toString().trim();
                        mViewModel.setGasKeyWord(search);
                        ThreadManager.getInstance().execute(() -> mViewModel.getGasData(SPUtil.getInstance().getString(SPName.PROJ_CODE)));
                    }, OKHttpUtil.SEARCH_DELAY_MILLIS);
                }
            });
            mGas.rvGas.setRowHeaderWidth(DensityUtil.dp2px(80));
            mGas.rvGas.getCellRecyclerView().setNestedScrollingEnabled(true);
            mGas.rvGas.getCellRecyclerView().setOnTouchListener((view, motionEvent) -> {
                return false;
            });
        }
        if (mGasAdapter == null) {
            mGasAdapter = new TableViewAdapter();
            mGas.rvGas.setAdapter(mGasAdapter);
        }
    }

    private void initWatchView() {
        if (mWatch == null) {
            mWatch = MainWatchBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
            mWatch.etWatch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    // 避免错乱
                    mHandler.removeCallbacksAndMessages(null);

                    mHandler.postDelayed(() -> {
                        String search = editable.toString().trim();
                        ThreadManager.getInstance().execute(() -> mViewModel.getWatchData(SPUtil.getInstance().getString(SPName.PROJ_CODE), search));
                    }, OKHttpUtil.SEARCH_DELAY_MILLIS);
                }
            });
            mWatch.ivShow.setOnClickListener(view -> {
                watchIsShow = !watchIsShow;
                mWatchAdapter.setShowOrHide(watchIsShow);
                mWatch.ivShow.setBackground(watchIsShow ? getDrawable(R.drawable.icon_sel_show) : getDrawable(R.drawable.icon_nor_close));
            });
        }
        initWatch();
    }

    private void initLockView() {
        if (mLock == null) {
            mLock = MainLockBinding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
            mLock.etWatch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    // 避免错乱
                    mHandler.removeCallbacksAndMessages(null);

                    mHandler.postDelayed(() -> {
                        String search = editable.toString().trim();
                        ThreadManager.getInstance().execute(() -> mViewModel.getLockData(SPUtil.getInstance().getString(SPName.PROJ_CODE), search));
                    }, OKHttpUtil.SEARCH_DELAY_MILLIS);
                }
            });
        }
        initLock();
    }

    private void init360View() {
        if (m360 == null) {
            m360 = Main360Binding.inflate(LayoutInflater.from(this), mBinding.llMainContent, false);
            m360.etWatch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    // 避免错乱
                    mHandler.removeCallbacksAndMessages(null);

                    mHandler.postDelayed(() -> {
                        String search = editable.toString().trim();
                        ThreadManager.getInstance().execute(() -> mViewModel.get360Data(SPUtil.getInstance().getString(SPName.PROJ_CODE), search));
                    }, OKHttpUtil.SEARCH_DELAY_MILLIS);
                }
            });
        }
        init360();
    }

    private void initWatch() {
        if (mWatchAdapter == null) {
            mWatchAdapter = new WatchAdapter(this);
            mWatch.rvWatch.setLayoutManager(new LinearLayoutManager(mContext));
            mWatch.rvWatch.setAdapter(mWatchAdapter);
            mWatch.rvWatch.setItemAnimator(null);
            mWatchAdapter.setShowInfo(false);//隐藏详情
            mWatchAdapter.setMainShow(true);//主页数据展示标识
        }
    }

    private void initLock() {
        if (mLockAdapter == null) {
            mLockAdapter = new MainLockAdapter(this);
            mLock.rvLock.setLayoutManager(new GridLayoutManager(mContext, 2));
            mLock.rvLock.setAdapter(mLockAdapter);
            mLock.rvLock.setItemAnimator(null);
        }
    }

    private void init360() {
        if (mPlant360Adapter == null) {
            mPlant360Adapter = new MainPlant360Adapter(this);
            m360.rv360.setLayoutManager(new GridLayoutManager(mContext, 2));
            m360.rv360.setAdapter(mPlant360Adapter);
            m360.rv360.setItemAnimator(null);
        }
    }

    private void initAlert() {
        if (mAlertAdapter == null) {
            mAlertAdapter = new AlertAdapter(this);
            mAlert.rvAlert.setLayoutManager(new LinearLayoutManager(mContext));
            mAlert.rvAlert.setAdapter(mAlertAdapter);
            mAlert.rvAlert.setItemAnimator(null);
        }
    }

    private void initUnsafeAct() {
        if (mUnsafeActAdapter == null) {
            mUnsafeActAdapter = new UnsafeActAdapter(this);
            mUnsafeAct.rvUnsafeAct.setLayoutManager(new LinearLayoutManager(mContext));
            mUnsafeAct.rvUnsafeAct.setAdapter(mUnsafeActAdapter);
            mUnsafeAct.rvUnsafeAct.setItemAnimator(null);
        }
    }

    @Override
    protected void initData() {
        mAlertCode = SPUtil.getInstance().getString(SPName.ALERT_CODE);
        mViewModel.setAlertKeyWord(mAlertCode);
        mProjId = SPUtil.getInstance().getString(SPName.PROJ_ID);
        mBinding.mainInfo.tvProjectName.setText(SPUtil.getInstance().getString(SPName.PROJ_NAME));
        mViewModel.setTagCodes(new ArrayList<>(Arrays.asList(SPUtil.getInstance().getString(SPName.TAG_CODE).split(","))));
        String tagListStr = SPUtil.getInstance().getString(SPName.TAG, "");
        if (!tagListStr.isEmpty()) {
            List<UserTagDto> userTagDtos = (List<UserTagDto>) GsonUtil.getInstance().fromJson(tagListStr, new TypeToken<List<UserTagDto>>() {
            }.getType());
            if (userTagDtos != null) {
                handleUserTag(userTagDtos);
            }
        }
        mViewModel.getData();
        startThread();

        //手表
        mWatchAdapter.setOnItemClickListener((v,p)->{
            queryInfoTagCode = TagCode.codeWatch;
            watchOldData = mWatchAdapter.getPositionData(p);
            mViewModel.getDeviceById(TagCode.codeWatch, watchOldData.getId());
        });

        //电子锁
        mLockAdapter.setOnItemClickListener((v,p)->{
            queryInfoTagCode = TagCode.codeLock;
            lockOldData = mLockAdapter.getPositionData(p);
            mViewModel.getDeviceById(TagCode.codeLock, lockOldData.getId());
        });
    }

    /**
     * 开启实时刷新
     */
    private void startThread() {
        if (mTimer == null) {
            mTimer = new Timer();
            mTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    if (mIsShow) {
                        try {
                            ThreadManager.getInstance().execute(() -> mViewModel.getMainData());
                        } catch (Exception e) {
                            Log.e(TAG, "run: ", e);
                        }
                    }
                }
            }, 60000, 60000); // 60秒钟执行一次
        }
    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {
        if (result.values().stream().allMatch(Boolean.TRUE::equals)) {
            configMap();
        } else {
            ToastUtil.showToast(R.string.no_have_per);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsShow = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsShow = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        Places.deinitialize();
        closePopupWindow();
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }
}